package Clock;

import ObservableHelperP.ObservableExternalTrigger;

import java.util.Observable;

/**
 * Created by Connor Madden.
 * User: Connor Madden
 * Date: 12/10/11
 * Time: 6:07 PM
 */
public class Clock extends Observable implements ClockI {
    long t;
    private boolean alive;
    private ObservableExternalTrigger killObservable;
    Thread clockThread;

    public Clock(long t) {
        this.t = t;
        alive = true;
    }

    public boolean start() {
        if (clockThread != null && clockThread.isAlive()) {
            return false;
        } else {
            clockThread = new Thread(new Runnable() {
                public void run() {
                    while (alive) {
                        try {
                            Thread.sleep(t);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        update();
                    }
                }
            });
            clockThread.setDaemon(true);
            clockThread.start();
            return true;
        }
    }

    public void kill() {
        alive = false;
        killObservable.setAndNotifyObservers();
    }

    public Observable getKillObservable() {
        return killObservable;
    }

    protected void update() {
        setChanged();
        notifyObservers();
    }

    public long getT() {
        return t;
    }

    public void setT(long t) {
        this.t = t;
    }
}
